package com.server.config.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.server.pojo.ResponseBean;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * @ClassName: RestfulAccessDeniedHandler
 * @Description: 访问接口没有权限时，自定义返回结果
 * @Author: SongHL
 * @Date: 2025/9/14
 */
@Component
public class RestfulAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");

        PrintWriter writer = response.getWriter();
        ResponseBean error = ResponseBean.error("权限不足，请联系管理员!");
        error.setCode(403);

        writer.write(new ObjectMapper().writeValueAsString(error));
        writer.flush();
        writer.close();

    }
}
